'use strict';

import axios from 'axios';
import router from '../router/index';

let config = {
  baseURL: window.baseIp
};

const _axios = axios.create(config);

let loginMsgState = false;
_axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    // 添加token
    const token = localStorage.token;
    config.headers.Authorization = token;
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    let { status, data, config } = response;
    if (status === 200) {
      // 判断响应数据类型
      if (
        config.responseType === 'blob' ||
        config.responseType === 'arraybuffer'
      ) {
        return response;
      } else {
        let { code, status, msg } = data;
        if (code !== 0 && status !== 200) {
          ElMessage.error(msg);
        }
        return data;
      }
    } else {
      return response;
    }
  },
  function (error) {
    // Do something with response error
    let { status, data, config } = error.response;
    if (!loginMsgState) {
      loginMsgState = true;
      // 清空token
      localStorage.token = '';
      // 保留跳转前页面
      sessionStorage.cachePageUrl = window.location.href;
      ElMessage({
        type: 'warning',
        message: '需要登录，2秒后将跳转到登录界面！',
        duration: 2000
      });
      setTimeout(() => {
        router.push('/login');
        loginMsgState = false;
      }, 2000);
    }
    if (status === 403) {
      // 如果是流，转回文字
      if (
        config.responseType === 'blob' ||
        config.responseType === 'arraybuffer'
      ) {
        let enc = new TextDecoder('utf-8');
        data = JSON.parse(enc.decode(new Uint8Array(data)));
        return Promise.reject(data);
      }
    }
    if (status === 500) {
      ElMessage.error(data.msg);
    }
    return Promise.reject(error);
  }
);

export default _axios;
